<template>
  <el-dialog
    :visible="visible"
    center
    :show-close="false"
    width="750px"
  >
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ renderTitle }}</span>
        <span
          class="el-icon-close g9 f26 poi"
          @click="handleCancel"
        ></span>
      </div>
    </div>

    <el-form :model="form" ref="form" label-width="100px" class="pl30 pr30">
      <el-form-item
        label="变量名"
        prop="varName"
        :rules="[
          {
            required: true,
            message: '变量名不能为空',
            trigger: 'change'
          }
        ]" >
        <el-input
          v-model.trim="form.varName"
          :maxlength="128"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="2"
          show-word-limit
          :maxlength="200"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="tr">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>

export default {
  name: 'TypeForm',
  data() {
    return {
      formType: 'ADD',
      id: 0,
      tempId: '',
      visible: false,
      confirmLoading: false,
      form: {}
    }
  },
  computed: {
    renderTitle() {
      return this.formType === 'ADD' ? '新建内置变量' : '编辑内置变量'
    }
  },
  methods: {
    add(values) {
      this.visible = true
      this.formType = 'ADD'
      this.$nextTick(() => {
        this.form = { varName: '', description: '' }
        this.$refs.form.clearValidate()
      })
    },

    edit(values) {
      this.visible = true
      this.formType = 'EDIT'
      const { id, tempId, varName, description } = values
      this.id = id
      this.tempId = tempId
      this.$nextTick(() => {
        const model = { varName, description }
        this.form = model
      })
    },

    async handleSubmit() {
      try {
        await this.$refs.form.validate()
        const model = {
          varName: this.form.varName.trim(),
          description: this.form.description.trim()
        }
        this.$emit('ok', Object.assign({}, model, { id: this.id, tempId: this.tempId, formType: this.formType }))
        this.handleCancel()
      } catch (error) {
        console.log(error)
      }
    },

    handleCancel() {
      this.resetForm()
      this.visible = false
    },

    resetForm() {
      this.id = 0
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style></style>
